package com.sgcc.nfc.lock.core.network.interceptor

import com.sgcc.nfc.lock.core.storage.TokenManager
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import okhttp3.Interceptor
import okhttp3.Response
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class AuthInterceptor @Inject constructor(
    private val tokenManager: TokenManager
) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val requestBuilder = chain.request().newBuilder()
        val token = runBlocking { tokenManager.accessToken.first() }
        if (!token.isNullOrBlank()) {
            val tokenType = runBlocking { tokenManager.tokenType.first() } ?: "Bearer"
            requestBuilder.addHeader("Authorization", "$tokenType $token")
        }
        val response = chain.proceed(requestBuilder.build())
        if (response.code == 401 || response.code == 403) {
            runBlocking { tokenManager.clear() }
        }
        return response
    }
}
